package com.jiang.utils;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/** MyBatis连接获取工具类 **/
public class MyBatisSessionFactory {

	private MyBatisSessionFactory() {

	}

	// 解决多线程的安全问题，用线程复制的池子
	private static ThreadLocal<SqlSession> threadlocal = new ThreadLocal<SqlSession>();
	private static SqlSessionFactory sqlSessionFactory = null;
	private static Reader reader = null;
	static {
		try {
			reader = Resources.getResourceAsReader("mybatis.cfg.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取连接工厂
	 * 
	 * @return
	 */
	public static SqlSessionFactory getSqlSessionFactory() {
		if (sqlSessionFactory == null) {
			rebuildFactory();
		}
		return sqlSessionFactory;
	}

	/**
	 * 获取连接
	 * 
	 * @return
	 */
	public static SqlSession getSqlSession() {

		SqlSession sqlSession = threadlocal.get();
		if (sqlSession == null) {
			sqlSession = getSqlSessionFactory().openSession();
			threadlocal.set(sqlSession);
		}
		return sqlSession;
	}

	/**
	 * 关闭连接
	 */
	public static void closeSqlSession() {
		SqlSession sqlSession = threadlocal.get();
		if (sqlSession != null) {
			threadlocal.set(null);
			sqlSession.close();
		}
	}

	/**
	 * 重建工厂
	 */
	private static void rebuildFactory() {
		try {
			reader = Resources.getResourceAsReader("mybatis.cfg.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
